package com.qianniu.napi.admin.web;

import akka.actor.ActorRef;
import akka.actor.Props;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.qianniu.napi.admin.entity.*;
import com.qianniu.napi.admin.entity.penum.XftypeEnum;
import com.qianniu.napi.admin.service.*;
import com.qianniu.napi.admin.service.akka.AkkaServer;
import com.qianniu.napi.admin.service.akka.FanActor;
import com.qianniu.napi.admin.service.akka.NewsActor;
import com.qianniu.napi.common.config.Constants;
import com.qianniu.napi.common.util.CheckUtil;
import com.qianniu.napi.common.util.ObjectUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * <p>
 * </p>
 *
 * @author chenxuebin
 * @since 2018-12-17
 */
@RestController
public class PyqController {

    private static final Logger logger = LoggerFactory.getLogger(PyqController.class);

    @Autowired
    private IPyqService pyqService;
    @Autowired
    private IPyqActService pyqActService;
    @Autowired
    private IStoreService storeService;
    @Autowired
    private IRedisService redisService;
    @Autowired
    private IOrderService orderService;
    @Autowired
    private IUserService userService;

    @RequestMapping("/api/pyq/list")
    @ResponseBody
    public Jinfo list(@RequestParam(value = "status", required = false) String status,
                      @RequestParam(value = "pageIndex", required = false) Integer pageIndex,
                      @RequestParam(value = "pageSize", required = false) Integer pageSize,
                      HttpServletRequest req) {
        Jinfo info = new Jinfo();
        if (pageSize == null) pageSize = 5;
        Page page = new Page(pageIndex, pageSize);

        Wrapper entity = new EntityWrapper<Pyq>()
                .eq("mpid", ObjectUtil.getMpid())
                .eq("state", 1).orderBy("id", false);

        Page<Pyq> pages = pyqService.selectPage(page, entity);

        List<Pyq> list = pages.getRecords();
        page = new Page(1, 50);
        for (Pyq item : list) {
            //更新浏览数
            logger.info("=====================pyq start AKKA_MSG_PYQ_VIEW at pyqid=" + item.getId());
            AkkaServer.system.actorOf(Props.create(NewsActor.class))
                    .tell(Constants.AKKA_MSG_PYQ_VIEW + "@" + item.getId(), ActorRef.noSender());

            Page<PyqAct> plist = pyqActService.selectPage(page, new EntityWrapper<PyqAct>()
                    .eq("mpid", ObjectUtil.getMpid())
                    .eq("act", 1)
                    .eq("pyqid", item.getId())
                    .eq("state", 1)
                    .orderBy("hid", true)
                    .orderBy("id", false));

            item.setHuifus(plist == null ? null : plist.getRecords());

            List<PyqAct> zans = pyqActService.selectList(new EntityWrapper<PyqAct>().setSqlSelect("id,uid,name,logo")
                    .eq("mid", ObjectUtil.getMid())
                    .eq("mpid", ObjectUtil.getMpid())
                    .eq("act", 2)
                    .eq("pyqid", item.getId())
                    .orderBy("id", true));

            PyqAct zan = pyqActService.selectOne(new EntityWrapper<PyqAct>().setSqlSelect("id,uid,name,logo")
                    .eq("uid", ObjectUtil.getUid())
                    .eq("mid", ObjectUtil.getMid())
                    .eq("mpid", ObjectUtil.getMpid())
                    .eq("act", 2)
                    .eq("pyqid", item.getId())
                    .orderBy("id", true));
            if (zan != null) item.setSelf(1);
            else item.setSelf(0);

            item.setZans(zans);

//            int views = pyqActService.selectCount(new EntityWrapper<PyqAct>().setSqlSelect("id,uid,name,logo")
//                    .eq("mid", ObjectUtil.getMid())
//                    .eq("mpid", ObjectUtil.getMpid())
//                    .eq("act", 3)
//                    .eq("pyqid", item.getId())
//                    .orderBy("id", true));
//            item.setViews(views);
        }

        info.setInfo(list);
        return info;
    }

    /*
     * 首页派单接口列表
     * 派单类别：type
     * 经度：lng
     * 纬度：lat
     * 第几页：pageIndex
     * 每页大小：pageSize
     */
    @RequestMapping("/api/pyq/hylist")
    @ResponseBody
    public Jinfo hylist(@RequestParam(value = "type", required = false) Integer type,
                        @RequestParam(value = "lng", required = false) Double lng,
                        @RequestParam(value = "lat", required = false) Double lat,
                        @RequestParam(value = "pageIndex", required = false) Integer pageIndex,
                        @RequestParam(value = "pageSize", required = false) Integer pageSize,
                        HttpServletRequest req) {
        Jinfo info = new Jinfo();
        if (pageSize == null) pageSize = 10;

        List<Pyq> list = pyqService.getHyList(pageIndex, pageSize, lat, lng, ObjectUtil.getMpid(), type, null);

        info.setInfo(list);
        return info;
    }

    @RequestMapping("/api/pyq/add")
    @ResponseBody
    public Jinfo pyqAdd(@Valid Pyq pyq,
                        HttpServletRequest req) {
        Jinfo info = new Jinfo();
        if (ObjectUtil.getSid() == null) {
            info.setCode(1);
            info.setMsg("当前用户非商家用户");
            return info;
        }
        User user = redisService.getUser();
        pyq.setMid(ObjectUtil.getMid());
        pyq.setMpid(ObjectUtil.getMpid());
        pyq.setUid(ObjectUtil.getUid());
        pyq.setState(1);
        pyq.setStatus(1);
        pyq.setSid(ObjectUtil.getSid());

        if (ObjectUtil.getSid() != null) {
            Store store = storeService.selectById(ObjectUtil.getSid());
            pyq.setPhone(store.getPhone());
            pyq.setLat(store.getLatitude());
            pyq.setLng(store.getLongitude());
            pyq.setMname(store.getName());
            pyq.setMlogo(store.getLogo() == null ? user.getAvatarPic() : store.getLogo());
            pyq.setMaddr(store.getAddress());
            pyq.setShengcode(store.getProvinceCode());
            pyq.setShicode(store.getCityCode());
            pyq.setXiancode(store.getDistrictCode());

        } else {
            User ruser = redisService.getUser();
            pyq.setPhone(ruser.getPhone());
            pyq.setMname(ruser.getNickName());
            pyq.setMlogo(ruser.getAvatarPic());
        }
        if (pyq.getId() == null) {
            pyq.setCreatetime(new Date());
        } else {
            pyq.setModifytime(new Date());
        }

        try {
            logger.info("=========pyq=" + JSON.toJSONString(pyq));
            pyq.insertOrUpdate();
        } catch (Exception e) {
            logger.error("======pyq.insert error", e);
        }
        return info;
    }


    @RequestMapping("/api/pyq/zan")
    @ResponseBody
    public Jinfo zan(@RequestParam("pyqid") Long pyqid) {
        Jinfo info = new Jinfo();


        PyqAct pyq = pyqActService.selectOne(new EntityWrapper<PyqAct>()
                .eq("pyqid", pyqid).eq("act", 2)
                .eq("uid", ObjectUtil.getUid()));

        if (pyq == null) {
            pyq = new PyqAct();
            pyq.setCreatetime(new Date());
            pyq.setMid(ObjectUtil.getMid());
            pyq.setMpid(ObjectUtil.getMpid());
            pyq.setUid(ObjectUtil.getUid());
            pyq.setPyqid(pyqid);
            pyq.setState(1);
            pyq.setAct(2);

            User user = redisService.getUser();
            pyq.setLogo(user.getAvatarPic());
            pyq.setName(user.getNickName());
            pyq.insert();

            info.setInfo(pyq);

            // 点赞奖励自己
            AkkaServer.system.actorOf(Props.create(FanActor.class))
                    .tell(Constants.AKKA_MSG_DIANZAN + "@" + user.getId() + "@" + user.getMpid() + "@" + pyqid, ActorRef.noSender());

        } else {
            pyq.setState(0);// 取消操作
            pyq.updateById();
        }
        return info;
    }

    @RequestMapping("/api/pyq/zancancel")
    @ResponseBody
    public Jinfo zanCancel(@RequestParam("pyqid") Long pyqid) {
        Jinfo info = new Jinfo();

        PyqAct pyq = pyqActService.selectOne(new EntityWrapper<PyqAct>().eq("pyqid", pyqid).eq("uid", ObjectUtil.getUid()));
        if (pyq == null) return info;

        pyq.setState(0);// 取消操作
        return info;
    }

    @RequestMapping("/api/pyq/huifudel")
    @ResponseBody
    public Jinfo huifudel(Long hfid) {
        Jinfo info = new Jinfo();
        PyqAct pyq = pyqActService.selectById(hfid);
        if (pyq == null) {
            info.setCode(1);
            info.setMsg("无权限操作");
            return info;
        }
        pyq.setState(-1);// 逻辑删除
        return info;
    }

    @RequestMapping("/api/pyq/huifu")
    @ResponseBody
    public Jinfo huifu(@Valid PyqAct pyq) {
        Jinfo info = new Jinfo();

        pyq.setCreatetime(new Date());
        pyq.setMid(ObjectUtil.getMid());
        pyq.setMpid(ObjectUtil.getMpid());
        pyq.setUid(ObjectUtil.getUid());

        pyq.setState(CheckUtil.checkMessage(pyq.getInfo(), ObjectUtil.getMpid().toString()) ? 1 : -1);
        pyq.setAct(1);
        pyq.setHid(0l);

        User user = redisService.getUser();
        pyq.setLogo(user.getAvatarPic());
        pyq.setName(user.getNickName());

        pyq.insert();
        info.setInfo(pyq);

        // 回复奖励自己
        AkkaServer.system.actorOf(Props.create(FanActor.class))
                .tell(Constants.AKKA_MSG_PINGLUN + "@" + user.getId() + "@" + user.getMpid() + "@" + pyq.getId(), ActorRef.noSender());
        info.setCode(pyq.getState() == -1 ? 4 : 0);
        return info;
    }

    @RequestMapping("/api/pyq/plhuifu")
    @ResponseBody
    public Jinfo plhuifu(@Valid PyqAct pyq) {
        Jinfo info = new Jinfo();

        pyq.setCreatetime(new Date());
        pyq.setMid(ObjectUtil.getMid());
        pyq.setMpid(ObjectUtil.getMpid());

        PyqAct pl = pyqActService.selectById(pyq.getHid());

        pyq.setHuid(pl.getUid());
        pyq.setHname(pl.getName());
        pyq.setHlogo(pl.getLogo());

        pyq.setState(CheckUtil.checkMessage(pyq.getInfo(), ObjectUtil.getMpid().toString()) ? 1 : -1);
        pyq.setAct(1);
        User user = redisService.getUser();
        pyq.setLogo(user.getAvatarPic());
        pyq.setName(user.getNickName());
        pyq.setUid(ObjectUtil.getUid());

        pyq.insert();
        info.setInfo(pyq);
        info.setCode(pyq.getState() == -1 ? 4 : 0);

        // 回复奖励自己
        AkkaServer.system.actorOf(Props.create(FanActor.class))
                .tell(Constants.AKKA_MSG_PINGLUN + "@" + user.getId() + "@" + user.getMpid() + "@" + pyq.getId(), ActorRef.noSender());

        return info;
    }

    @RequestMapping("/api/pyq/modify")
    @ResponseBody
    public Jinfo pyqUpdate(HttpServletRequest req, Pyq pyq) {
        Jinfo info = new Jinfo();
        pyq.setModifytime(new Date());

        pyq.setStatus(1);//修改之后默认重新审核
        pyq.updateById();

        return info;
    }

    @RequestMapping("/api/pyq/detail")
    @ResponseBody
    public Jinfo getPyqDetailById(@RequestParam("id") long id) {

        Jinfo info = new Jinfo();
        Pyq pyq = pyqService.selectById(id);

        List<PyqAct> huifus = pyqActService.selectList(new EntityWrapper<PyqAct>().setSqlSelect("id,pyqid,act,info,hid,name,logo")
                .eq("pyqid", id).eq("act", 1).eq("state", 1).orderBy("id", true).orderBy("hid", true));

//        for(PyqAct item: huifus){
//            List<PyqAct> plhuifus= pyqActService.selectList(new EntityWrapper<PyqAct>().setSqlSelect("id,pyqid,act,info,hid,name,logo")
//                    .eq("pyqid",id).eq("act",1).eq("state",1).eq("hid",item.getId()).orderBy("id",true));
//            item.setHuifus(plhuifus);
//        }

        List<PyqAct> zans = pyqActService.selectList(new EntityWrapper<PyqAct>().setSqlSelect("id,pyqid,act,name,logo")
                .eq("pyqid", id).eq("act", 2).eq("state", 1).orderBy("id", true));

        pyq.setHuifus(huifus);
        pyq.setZans(zans);

        info.setInfo(pyq);
        return info;
    }

    @RequestMapping("/api/pyq/hydetail")
    @ResponseBody
    public Jinfo getPyqhyDetailById(@RequestParam("id") long id,
                                    @RequestParam(value = "id", required = false) Integer acttype) {

        Jinfo info = new Jinfo();
        Pyq pyq = pyqService.selectById(id);

        Order order = orderService.selectOne(new EntityWrapper<Order>()
                .eq("xftype", XftypeEnum.paidan.getVal())
                .eq("gid", id));
        pyq.setOrder(order);

        if (acttype != null && acttype >= 1 && order.getJduid() != null) {
            User user = userService.selectById(order.getJduid());
            pyq.setJduser(user);
        }
        pyq.setViews(pyq.getViews() + 1);
        pyq.updateById();
        info.setInfo(pyq);
        return info;
    }

    @RequestMapping("/api/pyq/shenhe")
    @ResponseBody
    public Jinfo pyqshenhe(@RequestParam("id") long id, Integer state, Integer status) {

        Jinfo info = new Jinfo();
        Pyq pyq = new Pyq();
        pyq.setId(id);
        if (state != null) pyq.setState(state);
        if (status != null) pyq.setStatus(status);
        pyq.updateById();

        return info;
    }

    @RequestMapping("/api/pyq/shlist")
    @ResponseBody
    public Jinfo pyqshlist(@RequestParam(value = "pageIndex", required = false) Integer pageIndex,
                           @RequestParam(value = "pageSize", required = false) Integer pageSize) {

        Jinfo info = new Jinfo();
        if (pageSize == null) pageSize = 5;

        Page page = new Page(pageIndex, pageSize);
        Page<Pyq> pages = pyqService.selectPage(page, new EntityWrapper<Pyq>()
                .eq("mpid", ObjectUtil.getMpid())
                .eq("isdelete", -1)
                .orderBy("id", false));

        List<Pyq> list = pages.getRecords();
        List<Pyq> rlist = new ArrayList<Pyq>();
        for (Pyq item : list) {
            Order order = orderService.selectOne(new EntityWrapper<Order>()
                    .eq("gid", item.getId()));
            if (order == null || order.getStatus() <= 1) continue;

            if (order.getJduid() != null) {
                User jduser = userService.selectOne(new EntityWrapper<User>()
                        .setSqlSelect("id,phone,name,avatar_pic avatarPic")
                        .eq("id", order.getJduid()));
                item.setJduser(jduser);
                item.setOstatus(order.getStatus());
                item.setOstatusname(order.getStatus() == -1 ? "已取消" : order.getStatus() == 3 ? "进行中" : order.getStatus() == 4 ? "待确认" : "已完成");
            }
            rlist.add(item);
        }
        info.setInfo(rlist);
        return info;
    }

    @RequestMapping("/api/pyq/wode")
    @ResponseBody
    public Jinfo wode(@RequestParam(value = "pageIndex", required = false) Integer pageIndex,
                      @RequestParam(value = "pageSize", required = false) Integer pageSize) {

        Jinfo info = new Jinfo();
        if (pageSize == null) pageSize = 5;

        Page page = new Page(pageIndex, pageSize);
        Page<Pyq> pages = pyqService.selectPage(page, new EntityWrapper<Pyq>()
                .eq("mpid", ObjectUtil.getMpid())
                .eq("isdelete", -1)
                .eq("uid", ObjectUtil.getUid())
                .orderBy("id", false));
        List<Pyq> list = pages.getRecords();
        List<Pyq> rlist = new ArrayList<Pyq>();
        for (Pyq item : list) {
            Order order = orderService.selectOne(new EntityWrapper<Order>().eq("gid", item.getId()));
            if (order == null || order.getStatus() == 1) continue;
            if (order.getJduid() != null) {
//                ,carda,cardb
                User jduser = userService.selectOne(new EntityWrapper<User>()
                        .setSqlSelect("id,phone,name,avatar_pic avatarPic")
                        .eq("id", order.getJduid()));
                item.setJduser(jduser);
                item.setOstatus(order.getStatus());
                item.setOstatusname(order.getStatus() == -1 ? "已取消" : order.getStatus() == 3 ? "进行中" : order.getStatus() == 4 ? "待确认" : "已完成");
            }
            rlist.add(item);
        }
        info.setInfo(rlist);
        return info;
    }

    /*
     * 接单
     */
    @RequestMapping("/api/order/jiedan")
    @ResponseBody
    public Jinfo jiedan(Long id, HttpServletRequest req) {
        Jinfo json = new Jinfo();

        if (id == null) {
            json.setCode(4);
            json.setMsg("参数错误");
            return json;
        }
        Pyq pyq = pyqService.selectById(id);
        if (pyq == null) {
            json.setCode(4);
            json.setMsg("参数错误");
            return json;
        }
        User user = userService.selectById(ObjectUtil.getUid());
        if (user == null) {
            json.setCode(1);
            json.setMsg("必须先授权登录才能接单");
            return json;
        }
        if (user.getIsStaff() == null || user.getIsStaff() != 1) {
            json.setCode(1);
            json.setMsg("必须成功申请成为派单员才能接单");
            return json;
        }

        Order order = orderService.selectOne(new EntityWrapper<Order>()
                .eq("xftype", XftypeEnum.paidan.getVal())
                .eq("gid", id));

        if (order == null) {
            json.setCode(1);
            json.setMsg("派单信息有误");
            return json;
        }

        if (order != null && order.getJduid() != null) {
            json.setCode(1);
            json.setMsg("该单已被其他人接");
            return json;
        }
        logger.info("===========================order.getUid()=" + order.getUid());
        logger.info("===========================ObjectUtil.getUid()=" + ObjectUtil.getUid());
        if (order != null && order.getUid().intValue() == ObjectUtil.getUid().intValue()) {
            json.setCode(1);
            json.setMsg("不能接自己派单");
            return json;
        }

        order.setModifytime(new Date());
        order.setModifier(ObjectUtil.getUid());
        order.setJduid(ObjectUtil.getUid());
        order.setStatus(3);
        order.updateById();

        return json;
    }


    @RequestMapping("/api/pyq/mylist")
    @ResponseBody
    public Jinfo mylist(@RequestParam(value = "pageIndex", required = false) Integer pageIndex,
                        @RequestParam(value = "pageSize", required = false) Integer pageSize) {
        Jinfo info = new Jinfo();
        if (pageSize == null) pageSize = 5;
        Page page = new Page(pageIndex, pageSize);

        Wrapper entity = new EntityWrapper<Pyq>()
                .eq("mpid", ObjectUtil.getMpid())
                .eq("state", 1).orderBy("id", false);
        User ruser = redisService.getUser();
        if (ObjectUtil.getSid() != null) entity.eq("sid", ruser.getSid());

        Page<Pyq> pages = pyqService.selectPage(page, entity);

        List<Pyq> list = pages.getRecords();
        page = new Page(1, 50);
        for (Pyq item : list) {

            Page<PyqAct> plist = pyqActService.selectPage(page, new EntityWrapper<PyqAct>()
                    .eq("mpid", ObjectUtil.getMpid())
                    .eq("act", 1)
                    .eq("pyqid", item.getId())
                    .eq("state", 1)
                    .orderBy("hid", true)
                    .orderBy("id", false));

            item.setHuifus(plist == null ? null : plist.getRecords());

            List<PyqAct> zans = pyqActService.selectList(new EntityWrapper<PyqAct>().setSqlSelect("id,uid,name,logo")
                    .eq("mid", ObjectUtil.getMid())
                    .eq("mpid", ObjectUtil.getMpid())
                    .eq("act", 2)
                    .eq("pyqid", item.getId())
                    .orderBy("id", true));

            PyqAct zan = pyqActService.selectOne(new EntityWrapper<PyqAct>().setSqlSelect("id,uid,name,logo")
                    .eq("uid", ObjectUtil.getUid())
                    .eq("mid", ObjectUtil.getMid())
                    .eq("mpid", ObjectUtil.getMpid())
                    .eq("act", 2)
                    .eq("pyqid", item.getId())
                    .orderBy("id", true));
            if (zan != null) item.setSelf(1);
            else item.setSelf(0);

            item.setZans(zans);

            int views = pyqActService.selectCount(new EntityWrapper<PyqAct>().setSqlSelect("id,uid,name,logo")
                    .eq("mid", ObjectUtil.getMid())
                    .eq("mpid", ObjectUtil.getMpid())
                    .eq("act", 3)
                    .eq("pyqid", item.getId())
                    .orderBy("id", true));
            item.setViews(views);
        }
        info.setInfo(list);
        return info;
    }


    @RequestMapping("/api/pyq/delete")
    @ResponseBody
    public Jinfo pyqDelete(@RequestParam("id") long id) {
        logger.info("===========================pyqDelete id=" + id);
        Jinfo info = new Jinfo();
        Pyq pyq = new Pyq();
        pyq.setId(id);
        pyq.deleteById();

        return info;
    }
}
